package es.unex.meigas.gvsig.core;

import com.hardcode.gdbms.engine.values.Value;
import com.iver.cit.gvsig.project.documents.table.ProjectTable;

import es.unex.meigas.dataObjects.IRecord;
import es.unex.meigas.dataObjects.IRecordsetIterator;
import es.unex.meigas.dataObjects.RecordImpl;
import es.unex.meigas.exceptions.IteratorException;

public class gvRecordsetIterator implements IRecordsetIterator {

	private Object m_Object;
	long m_iIndex;

	public gvRecordsetIterator(Object obj) {

		m_Object = obj;
		m_iIndex = 0;

	}

	public boolean hasNext() {

		long iRecordCount = 0;
		try{
			if (m_Object instanceof TableMemoryDriver) {
				TableMemoryDriver table = (TableMemoryDriver) m_Object;
				iRecordCount = table.getRowCount();
			}
			else{
				ProjectTable table = (ProjectTable) m_Object;
				iRecordCount = table.getModelo().getRowCount();
			}
		}
		catch(Exception e){
			e.printStackTrace();
		}

		return iRecordCount > m_iIndex;

	}

	public IRecord next() throws IteratorException {

		IRecord record = null;
		int iFieldCount;
		try{
			if (m_Object instanceof TableMemoryDriver) {
				TableMemoryDriver table = (TableMemoryDriver) m_Object;
				iFieldCount = table.getFieldCount();
				Object[] obj = new Object[iFieldCount];
				for (int i = 0; i < iFieldCount; i++) {
					obj[i] = table.getFieldValue(m_iIndex, i);
				}
				record = new RecordImpl(obj);
			}
			else{
				ProjectTable table = (ProjectTable) m_Object;
				Value[] obj = table.getModelo().getRecordset().getRow(m_iIndex);
				record = new RecordImpl(DataTools.getSextanteValues(obj));
			}
		}
		catch(Exception e){
			m_iIndex++;
			throw new IteratorException();
		}

		m_iIndex++;

		return record;

	}

	public void close() {}

}
